/*
 * 版权所有(C)，上海海鼎信息工程股份有限公司，lizhixing，所有权利保留。
 * <p>
 * 项目名：	boot-demo
 * 文件名：	UserServiceImpl
 * 模块说明：
 * 修改历史：
 * 2022/1/10 - lizhixing - 创建。
 */
package com.lovely602.boot.bootdemo.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.lovely602.boot.bootdemo.dao.jpa.user.UserRepository;
import com.lovely602.boot.bootdemo.domain.user.User;
import com.lovely602.boot.bootdemo.service.UserService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lizhixing
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

  @Autowired
  private UserRepository userRepository;

  @Override
  public User findById(String id) {
    Assert.notNull(id, "id");
    Optional<User> userOptional = userRepository.findById(id);
    return userOptional.orElse(null);
  }

  @Override
  public User findByUsername(String username) {
    Assert.notNull(username, "username");
    return userRepository.findByUsername(username);
  }

  @Override
  public List<User> findAll() {
    return userRepository.findAll();
  }

  @Transactional
  @Override
  public User save(User user) {
    Assert.notNull(user, "user");
    Assert.notNull(user.getId(), "userId");
    return userRepository.save(user);
  }

  @Transactional
  @Override
  public User modify(User user) {
    Assert.notNull(user, "user");
    Assert.notNull(user.getId(), "userId");
    userRepository.deleteById(user.getId());
    return userRepository.save(user);
  }

  @Transactional
  @Override
  public void delete(String id) {
    Assert.notNull(id, "id");
    userRepository.deleteById(id);
  }

  @Override
  public Page<User> findAll(Pageable pageable) {
    return userRepository.findAll(pageable);
  }
}
